#include "../Server.hpp"
#include <iostream>
#include <string.h>
#include <string>
#include <vector>

std::unordered_map<int,ConnectionPtr> hash;
static int connid = 0;
LoopThreadPool *pool;

void connection_cancel(const ConnectionPtr &cp)
{
    hash.erase(cp->GetConnid());
    DEBUG_LOG("%d号连接已从哈希表删除!",cp->GetSockfd());
}

void connected_handle(const ConnectionPtr &cp)
{
    std::cout << cp->GetSockfd() << "号连接已连接!" << std::endl;
}

void message_handle(const ConnectionPtr &cp,Buffer *buf)
{
    std::string str;
    buf->Read(str);
    DEBUG_LOG("接收到新消息: %s",str.c_str());

    cp->Send((void *)str.c_str(),str.size());
}

void any_handle(const ConnectionPtr &cp)
{
    DEBUG_LOG("没啥事...");
}

void hendle_accept(EventLoop *pl,Channel *pc,Socket *s)
{
    int connfd = s->Accept();
    std::cout << "获取到新连接: " << connfd << std::endl;
    ++connid;
    ConnectionPtr conn(new Connection(pool->NextLoop(),connid,connfd));
    conn->StartInactivBroken(3);

    conn->SetConnectedCallBack(std::bind(connected_handle,std::placeholders::_1));
    conn->SetClosedCallBack(std::bind(connection_cancel,std::placeholders::_1));
    conn->SetAnyCallBack(std::bind(any_handle,std::placeholders::_1));
    conn->SetMessageCallBack(std::bind(message_handle,std::placeholders::_1,std::placeholders::_2));
    conn->Established();
    hash.insert(std::make_pair(connid,conn));
}

int main()
{
    Socket *listen = new Socket();// 创建监听套接字
    listen->Create(true);// true->启动地址重用
    listen->Bind(9090);
    listen->Listen();// 启动监听
    
    EventLoop *pl = new EventLoop();// Poller对象:负责监听
    pool = new LoopThreadPool(pl);
    pool->SetThreadCount(2);
    pool->Create();

    Channel *listen_ch = new Channel(pl,listen->GetFd());// 为监听套接字创建Channel对象，方便Poller管理
    listen_ch->SetReadCallBack(std::bind(hendle_accept,pl,listen_ch,listen));// 设置可读事件触发后的回调(实际上就是接收连接套接字)
    listen_ch->SetCurrentEvents(EPOLLIN);

    pl->Start();// 该函数会将触发的Channel对象放入vector中

    listen->Close();
    delete listen;
    return 0;
}